import { createRouter, createWebHistory } from 'vue-router'
import AnimalView from '../views/AnimalView.vue'
import AnimeView from '../views/AnimeView.vue'
import CarView from '../views/CarView.vue'
import ComicView from '../views/ComicView.vue'
import DiscoverView from '../views/DiscoverView.vue'
import EntertainmentView from '../views/EntertainmentView.vue'
import FoodView from '../views/FoodView.vue'
import GameView from '../views/GameView.vue'
import HelpView from '../views/HelpView.vue'
import HomeView from '../views/HomeView.vue'
import JoinContactView from '../views/JoinContactView.vue'
import KnowledgeView from '../views/KnowledgeView.vue'
import LifeView from '../views/LifeView.vue'
import LoginView from '../views/LoginView.vue'
import MessageView from '../views/MessageView.vue'
import MovieView from '../views/MovieView.vue'
import MusicDetailView from '../views/MusicDetailView.vue'
import MusicView from '../views/MusicView.vue'
import NovelView from '../views/NovelView.vue'
import PeripheryView from '../views/PeripheryView.vue'
import ProfileView from '../views/ProfileView.vue'
import RegisterView from '../views/RegisterView.vue'
import SportsView from '../views/SportsView.vue'
import StudyView from '../views/StudyView.vue'
import TechView from '../views/TechView.vue'
import TVShowView from '../views/TVShowView.vue'
import UploadPageView from '../views/UploadPageView.vue'
import UploadView from '../views/UploadView.vue'
import VarietyShowView from '../views/VarietyShowView.vue'
import VideoDetailView from '../views/VideoDetailView.vue'
import VipView from '../views/VipView.vue'
import VirtualIdolView from '../views/VirtualIdolView.vue'
import VisionView from '../views/VisionView.vue'


// 后台管理页面 - 懒加载
const AdminLayout = () => import('../views/admin/AdminLayout.vue')
const DashboardView = () => import('../views/admin/DashboardView.vue')
const UsersView = () => import('../views/admin/UsersView.vue')
const VideosView = () => import('../views/admin/VideosView.vue')
const CategoriesView = () => import('../views/admin/CategoriesView.vue')
const TagsView = () => import('../views/admin/TagsView.vue')
const CommentsView = () => import('../views/admin/CommentsView.vue')
const SettingsView = () => import('../views/admin/SettingsView.vue')
const FeedbacksView = () => import('../views/admin/FeedbacksView.vue')
const AnalyticsView = () => import('../views/admin/AnalyticsView.vue')
const LogsView = () => import('../views/admin/LogsView.vue')
const TopicsView = () => import('../views/admin/TopicsView.vue')
const ActivitiesView = () => import('../views/admin/ActivitiesView.vue')
const AnimesView = () => import('../views/admin/AnimesView.vue')
const MembersView = () => import('../views/admin/MembersView.vue')
const StatisticsView = () => import('../views/admin/StatisticsView.vue')


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  scrollBehavior(to, from, savedPosition) {
    return { top: 0 }
  },
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: {
        title: '首页',
        keepAlive: true
      }
    },
    {
      path: '/live',
      name: 'live',
      component: () => import('../views/LiveView.vue'),
      meta: {
        title: '直播间'
      }
    },
  {
    path: '/live/:id',
    name: 'liveRoom',
    component: () => import('../views/LiveRoomView.vue'),
    meta: {
      title: '直播间详情'
    }
  },
  {
    path: '/user/:id',
    name: 'userProfile',
    component: () => import('../views/UserProfileView.vue'),
    meta: {
      title: '用户个人中心'
    }
  },
  {
    path: '/search/:keyword?',
    name: 'searchResult',
    component: () => import('../views/SearchResultView.vue'),
    meta: {
      title: '搜索结果'
    },
    props: true
  },
    {
      path: '/discover',
      name: 'discover',
      component: DiscoverView,
      meta: {
        title: '发现',
        keepAlive: true
      }
    },

    {
      path: '/message',
      name: 'message',
      component: MessageView,
      meta: {
        title: '消息',
        keepAlive: true
      }
    },
    {
      path: '/profile',
      name: 'profile',
      component: ProfileView,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView
    },
    {
      path: '/music/:id',
      name: 'musicDetail',
      component: MusicDetailView
    },
    {
      path: '/video/:id',
      name: 'videoDetail',
      component: VideoDetailView
    },
    {
      path: '/vip',
      name: 'vip',
      component: VipView
    },
    {
      path: '/help',
      name: 'help',
      component: HelpView,
      meta: {
        title: '帮助中心'
      }
    },
    {
      path: '/anime',
      name: 'anime',
      component: AnimeView
    },
    {
      path: '/music',
      name: 'music',
      component: MusicView
    },
    {
      path: '/game',
      name: 'game',
      component: GameView
    },
    {
      path: '/entertainment',
      name: 'entertainment',
      component: EntertainmentView
    },
    {
      path: '/knowledge',
      name: 'knowledge',
      component: KnowledgeView
    },
    {
      path: '/tech',
      name: 'tech',
      component: TechView
    },
    {
      path: '/life',
      name: 'life',
      component: LifeView
    },
    {
      path: '/variety',
      name: 'variety',
      component: VarietyShowView
    },
    {
      path: '/upload',
      name: 'upload',
      component: UploadPageView,
      meta: { requiresAuth: true, title: '创作投稿中心' }
    },
    {
      path: '/upload-old',
      name: 'upload-old',
      component: UploadView,
      meta: { requiresAuth: true, title: '创作投稿（旧版）' }
    },
    {
      path: '/food',
      name: 'food',
      component: FoodView
    },
    {
      path: '/sports',
      name: 'sports',
      component: SportsView
    },
    {
      path: '/car',
      name: 'car',
      component: CarView
    },
    {
      path: '/animal',
      name: 'animal',
      component: AnimalView
    },
    {
      path: '/movie',
      name: 'movie',
      component: MovieView
    },
    {
      path: '/tv',
      name: 'tv',
      component: TVShowView
    },
    {
      path: '/comic',
      name: 'comic',
      component: ComicView
    },
    {
      path: '/novel',
      name: 'novel',
      component: NovelView
    },
    {
      path: '/virtual',
      name: 'virtual',
      component: VirtualIdolView
    },
    {
      path: '/study',
      name: 'study',
      component: StudyView,
      meta: {
        title: '学习资源'
      }
    },
    {
      path: '/periphery',
      name: 'periphery',
      component: PeripheryView,
      meta: {
        title: '周边商城'
      }
    },
    {
      path: '/vision',
      name: 'vision',
      component: VisionView,
      meta: {
        title: '视界无界'
      }
    },
    {
      path: '/join-contact',
      name: 'joinContact',
      component: JoinContactView,
      meta: {
        title: '加入我们 & 联系我们'
      }
    },

    
    // 后台管理系统路由 - 将后台登录重定向到普通登录页面
    {
      path: '/admin/login',
      redirect: '/login'
    },
    {
      path: '/admin',
      component: AdminLayout,
      meta: {
        requiresAdmin: true
      },
      children: [
        {
          path: '',
          redirect: '/admin/dashboard'
        },
        {
          path: 'dashboard',
          name: 'adminDashboard',
          component: DashboardView,
          meta: {
            title: '控制台 - 管理后台'
          }
        },
        {
      path: 'users',
      name: 'adminUsers',
      component: UsersView,
      meta: {
        title: '用户管理 - 管理后台'
      }
    },
        {
          path: 'videos',
          name: 'adminVideos',
          component: VideosView,
          meta: {
            title: '视频管理 - 管理后台'
          }
        },
        {
          path: 'categories',
          name: 'adminCategories',
          component: CategoriesView,
          meta: {
            title: '分类管理 - 管理后台'
          }
        },
        {
          path: 'tags',
          name: 'adminTags',
          component: TagsView,
          meta: {
            title: '标签管理 - 管理后台'
          }
        },
        {
          path: 'comments',
          name: 'adminComments',
          component: CommentsView,
          meta: {
            title: '评论管理 - 管理后台'
          }
        },
        {
          path: 'feedbacks',
          name: 'adminFeedbacks',
          component: FeedbacksView,
          meta: {
            title: '反馈管理 - 管理后台'
          }
        },
        {
          path: 'settings',
          name: 'adminSettings',
          component: SettingsView,
          meta: {
            title: '系统设置 - 管理后台',
            requiresSuperAdmin: true
          }
        },
        {
          path: 'analytics',
          name: 'adminAnalytics',
          component: AnalyticsView,
          meta: {
            title: '数据分析 - 管理后台'
          }
        },
        {
          path: 'logs',
          name: 'adminLogs',
          component: LogsView,
          meta: {
            title: '系统日志 - 管理后台'
          }
        },
        {
          path: 'topics',
          name: 'adminTopics',
          component: TopicsView,
          meta: {
            title: '话题管理 - 管理后台'
          }
        },
        {
          path: 'activities',
          name: 'adminActivities',
          component: ActivitiesView,
          meta: {
            title: '活动管理 - 管理后台'
          }
        },
        {
          path: 'animes',
          name: 'adminAnimes',
          component: AnimesView,
          meta: {
            title: '动漫管理 - 管理后台'
          }
        },
        {
          path: 'members',
          name: 'adminMembers',
          component: MembersView,
          meta: {
            title: '会员管理 - 管理后台'
          }
        },
        {
          path: 'statistics',
          name: 'adminStatistics',
          component: StatisticsView,
          meta: {
            title: '数据统计 - 管理后台'
          }
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title || 'Vue 应用'
  
  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin) {
    const isAdminLoggedIn = localStorage.getItem('adminLoggedIn') === 'true'
    const adminUser = JSON.parse(localStorage.getItem('adminUser'))
    
    // 检查是否需要超级管理员权限（仅限管理员）
    if (to.meta.requiresSuperAdmin && (!adminUser || adminUser.role !== 'admin')) {
      alert('权限不足，只有超级管理员可以访问此页面')
      next('/admin/dashboard')
      return
    }
    
    if (!isAdminLoggedIn) {
      // 重定向到普通登录页面，而不是后台登录页面
      next('/login')
      return
    }
  }
  
  // 普通用户登录验证
  if (to.meta.requiresAuth) {
    // 这里可以添加普通用户的登录验证逻辑
    const isLoggedIn = !!localStorage.getItem('currentUser')
    if (!isLoggedIn) {
      next({ name: 'login' })
      return
    }
  }
  
  // 已登录管理员访问普通登录页时重定向到后台控制台
  if (to.name === 'login' && localStorage.getItem('adminLoggedIn') === 'true') {
    next('/admin/dashboard')
    return
  }
  
  // 已登录用户访问登录/注册页时重定向
  if ((to.name === 'login' || to.name === 'register') && localStorage.getItem('currentUser')) {
    next({ name: 'home' })
    return
  }
  
  // 确保不会自动重定向到登录页面，始终允许访问首页和公开页面
  next()
})

router.afterEach(function() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
})

export default router
